<template>
  <div class="packages-page">
    <!-- 搜索表单 -->
    <el-card class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="套餐状态">
          <el-select v-model="searchForm.is_active" placeholder="请选择状态" clearable>
            <el-option label="已上架" :value="true" />
            <el-option label="已下架" :value="false" />
          </el-select>
        </el-form-item>

        <el-form-item label="套餐类型">
          <el-select v-model="searchForm.package_type" placeholder="请选择类型" clearable>
            <el-option label="发布公司套餐" value="paid" />
            <el-option label="聊天消息套餐" value="chat_message" />
            <el-option label="查看手机号套餐" value="contact_view" />
            <el-option label="本地服务套餐" value="local_service" />
          </el-select>
        </el-form-item>

        <el-form-item label="搜索关键词">
          <el-input
            v-model="searchForm.search"
            placeholder="请输入套餐名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 套餐列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>套餐列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleCreate">
              <el-icon><Plus /></el-icon>
              新增套餐
            </el-button>
            <el-button @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="packageList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />

        <el-table-column prop="title" label="套餐名称" min-width="150" />

        <el-table-column prop="description" label="套餐描述" min-width="200">
          <template #default="{ row }">
            {{ row.description || '无描述' }}
          </template>
        </el-table-column>

        <el-table-column prop="price" label="价格" width="120">
          <template #default="{ row }">
            ¥{{ row.price.toFixed(2) }}
          </template>
        </el-table-column>

        <el-table-column prop="credits_amount" label="包含条数" width="120">
          <template #default="{ row }">
            {{ row.credits_amount }} 条
          </template>
        </el-table-column>

        <el-table-column prop="package_type" label="套餐类型" width="120">
          <template #default="{ row }">
            <el-tag
              :type="getPackageTypeTagType(row.package_type)"
            >
              {{ getPackageTypeLabel(row.package_type) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="row.is_active ? 'success' : 'danger'"
              class="status-tag"
            >
              {{ row.is_active ? '已上架' : '已下架' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(row)"
              >
                编辑
              </el-button>

              <el-button
                :type="row.is_active ? 'warning' : 'success'"
                size="small"
                @click="handleToggleStatus(row)"
              >
                {{ row.is_active ? '下架' : '上架' }}
              </el-button>

              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 创建/编辑套餐对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑套餐' : '新增套餐'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="packageForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="套餐名称" prop="title">
          <el-input
            v-model="packageForm.title"
            placeholder="请输入套餐名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="套餐描述" prop="description">
          <el-input
            v-model="packageForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入套餐描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="套餐价格" prop="price">
          <el-input-number
            v-model="packageForm.price"
            :min="0"
            :max="9999.99"
            :precision="2"
            :step="0.01"
            placeholder="请输入价格"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="包含条数" prop="credits_amount">
          <el-input-number
            v-model="packageForm.credits_amount"
            :min="1"
            :max="1000"
            placeholder="请输入条数"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="套餐类型" prop="package_type">
          <el-select
            v-model="packageForm.package_type"
            placeholder="请选择套餐类型"
            style="width: 100%"
          >
            <el-option label="发布公司套餐" value="paid" />
            <el-option label="聊天消息套餐" value="chat_message" />
            <el-option label="查看手机号套餐" value="contact_view" />
            <el-option label="本地服务套餐" value="local_service" />
          </el-select>
        </el-form-item>

        <el-form-item label="套餐状态" prop="is_active">
          <el-switch
            v-model="packageForm.is_active"
            active-text="上架"
            inactive-text="下架"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { packageApi, type Package, type PackageListParams, type CreatePackageParams } from '@/api/admin'

// 响应式数据
const loading = ref(false)
const packageList = ref<Package[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()

// 搜索表单
const searchForm = reactive<PackageListParams>({
  is_active: undefined,
  package_type: undefined,
  search: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 套餐表单
const packageForm = reactive<CreatePackageParams>({
  title: '',
  description: '',
  price: 0,
  credits_amount: 1,
  package_type: 'paid',
  is_active: true
})

// 当前编辑的套餐ID
const currentPackageId = ref<number | null>(null)

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入套餐名称', trigger: 'blur' },
    { min: 1, max: 50, message: '套餐名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入套餐价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能为负数', trigger: 'blur' }
  ],
  credits_amount: [
    { required: true, message: '请输入包含条数', trigger: 'blur' },
    { type: 'number', min: 1, message: '条数必须大于0', trigger: 'blur' }
  ],
  package_type: [
    { required: true, message: '请选择套餐类型', trigger: 'change' }
  ]
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString()
}

// 获取套餐类型标签类型
const getPackageTypeTagType = (packageType: string) => {
  switch (packageType) {
    case 'chat_message':
      return 'info'
    case 'contact_view':
      return 'warning'
    case 'local_service':
      return 'success'
    case 'paid':
    default:
      return 'primary'
  }
}

// 获取套餐类型显示标签
const getPackageTypeLabel = (packageType: string) => {
  switch (packageType) {
    case 'paid':
      return '发布公司套餐'
    case 'chat_message':
      return '聊天消息套餐'
    case 'contact_view':
      return '查看手机号套餐'
    case 'local_service':
      return '本地服务套餐'
    default:
      return '未知'
  }
}

// 获取套餐列表
const getPackageList = async () => {
  loading.value = true
  try {
    const params: PackageListParams = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }

    const response = await packageApi.getList(params)
    packageList.value = response.data
    pagination.total = response.pagination.total
  } catch (error) {
    console.error('获取套餐列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getPackageList()
}

// 重置搜索
const handleReset = () => {
  searchForm.is_active = undefined
  searchForm.package_type = undefined
  searchForm.search = ''
  pagination.page = 1
  getPackageList()
}

// 刷新
const handleRefresh = () => {
  getPackageList()
}

// 新增套餐
const handleCreate = () => {
  isEdit.value = false
  currentPackageId.value = null
  resetForm()
  dialogVisible.value = true
}

// 编辑套餐
const handleEdit = async (pkg: Package) => {
  isEdit.value = true
  currentPackageId.value = pkg.id

  packageForm.title = pkg.title
  packageForm.description = pkg.description || ''
  packageForm.price = pkg.price
  packageForm.credits_amount = pkg.credits_amount
  packageForm.package_type = pkg.package_type
  packageForm.is_active = pkg.is_active

  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  packageForm.title = ''
  packageForm.description = ''
  packageForm.price = 0
  packageForm.credits_amount = 1
  packageForm.package_type = 'paid'
  packageForm.is_active = true

  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    if (isEdit.value && currentPackageId.value) {
      await packageApi.update(currentPackageId.value, packageForm)
      ElMessage.success('套餐更新成功')
    } else {
      await packageApi.create(packageForm)
      ElMessage.success('套餐创建成功')
    }

    dialogVisible.value = false
    getPackageList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('提交套餐失败:', error)
    }
  }
}

// 切换状态
const handleToggleStatus = async (pkg: Package) => {
  try {
    const action = pkg.is_active ? '下架' : '上架'
    await ElMessageBox.confirm(`确定要${action}套餐 "${pkg.title}" 吗？`, `确认${action}`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await packageApi.updateStatus(pkg.id, !pkg.is_active)
    ElMessage.success(`套餐${action}成功`)
    getPackageList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('切换套餐状态失败:', error)
    }
  }
}

// 删除套餐
const handleDelete = async (pkg: Package) => {
  try {
    await ElMessageBox.confirm(`确定要删除套餐 "${pkg.title}" 吗？此操作不可恢复！`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await packageApi.delete(pkg.id)
    ElMessage.success('套餐删除成功')
    getPackageList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除套餐失败:', error)
    }
  }
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  getPackageList()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page
  getPackageList()
}

// 初始化
onMounted(() => {
  getPackageList()
})
</script>

<style scoped>
.packages-page {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.status-tag {
  margin-right: 5px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  align-items: center;
}

.action-buttons .el-button {
  margin: 0;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

@media (max-width: 768px) {
  .packages-page {
    padding: 15px;
  }

  .el-table {
    font-size: 12px;
  }

  .el-pagination {
    text-align: center;
  }

  .action-buttons {
    gap: 4px;
  }

  .action-buttons .el-button {
    font-size: 11px;
    padding: 4px 8px;
  }
}
</style>
